package com.wh.demo_test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class CounterMainAtomic {
	
	static class Counter {
		
		private AtomicInteger count = new AtomicInteger(0);
		private	CountDownLatch countDownLatch;	//进行线程阻塞
		
		public Counter(CountDownLatch countDownLatch) {
			super();
			this.countDownLatch = countDownLatch;
		}

		public void incr() {
			try {
				//为了使效果明显，线程沉睡1毫秒
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			//count.set(count.get() + 1);	//这一步并非原子操作
			count.incrementAndGet();	//这一步才是原子操作
			countDownLatch.countDown(); //没执行玩一个线程减去1
		}
		
		public AtomicInteger getCount() {
			return count;
		}
		
	}
	
	public static void main(String[] args) {
		//同时启动1000个线程，去进行i++计算，看看实际结果
		CountDownLatch countDownLatch = new CountDownLatch(10000);
		final Counter counter = new Counter(countDownLatch);
		for(int i = 0; i < 10000; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					counter.incr();
				}
			}).start();
		}
		try {
			countDownLatch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(counter.getCount());
	}
}
